package com.boot.mall.third.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.boot.mall.third.service.OssService;
import com.boot.mall.third.utils.ConstantPropertiesUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    //上传头像到OSS
    @Override
    public String uploadFileAvatar(MultipartFile file) {

        //通过工具类获取属性
        String endpoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;

        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            // 上传输入流
            InputStream inputStream = file.getInputStream();
            // 获取文件名称
            String filename = file.getOriginalFilename();
            //将文件名重新命名，UUID随机值加后缀名
            filename = UUID.randomUUID().toString().replaceAll("-","")
                    + filename.substring(filename.lastIndexOf("."));
            //将文件设置在某个文件下
            filename = "guli-shop/" + filename;
            // 调用方法实现上传
            ossClient.putObject(bucketName, filename, inputStream);
            // 关闭OSSClient
            ossClient.shutdown();
            // 返回的阿里云结果路径
            // https://huihui-avatar.oss-cn-hangzhou.aliyuncs.com/pic01.jpeg
            String resultPath = "https://"+bucketName+"."+endpoint+"/"+filename;
            return resultPath;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
